package controller

import (
	"aqchain/pkg/entity"
	"aqchain/pkg/log"
	"aqchain/pkg/model"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"gorm.io/gorm"
	"net/http"
)

// GetSale 获取定价交易信息
func (c *Controller) GetSale(ctx *gin.Context) {
	// 参数绑定
	var params entity.GetSaleUri
	err := ctx.BindUri(&params)
	if err != nil {
		log.Logger.Debug("error", zap.Error(err), zap.String("code", errParams.Error()))
		ctx.JSON(http.StatusBadRequest, ErrorResponse(errParams))
		return
	}
	// 检查作品
	var itemRecord model.Item
	err = c.db.Where(model.Item{DCI: params.DCI}).First(&itemRecord).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			log.Logger.Debug("error", zap.Error(err), zap.String("code", errItemNotExist.Error()))
			ctx.JSON(http.StatusBadRequest, ErrorResponse(errItemNotExist))
			return
		} else {
			log.Logger.Debug("error", zap.Error(err), zap.String("code", errDBError.Error()))
			ctx.JSON(http.StatusInternalServerError, ErrorResponse(errDBError))
			return
		}
	}
	// 获取交易状态
	var record model.Sale
	err = c.db.Where(model.Sale{DCI: params.DCI}).First(&record).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			log.Logger.Debug("error", zap.Error(err), zap.String("code", errSaleNotExist.Error()))
			ctx.JSON(http.StatusOK, ErrorResponse(errSaleNotExist))
		} else {
			log.Logger.Debug("error", zap.Error(err), zap.String("code", errDBError.Error()))
			ctx.JSON(http.StatusInternalServerError, ErrorResponse(errDBError))
			return
		}
	}
	data := entity.Sale{
		DCI:    record.DCI,
		Seller: record.Seller,
		Buyer:  record.Buyer,
		Price:  record.Price,
	}
	ctx.JSON(http.StatusOK, SuccessResponse(data))
}

// GetSales 获取交易状态集合
func (c *Controller) GetSales(ctx *gin.Context) {
	var params entity.GetSalesQuery
	err := ctx.BindQuery(&params)
	if err != nil {
		log.Logger.Debug("error", zap.Error(err), zap.String("code", errParams.Error()))
		ctx.JSON(http.StatusBadRequest, ErrorResponse(errParams))
		return
	}
	var record []entity.Sale
	// 查询交易状态集合 用到了左连接 效率未知
	db := c.db.Select(
		"items.dci as dci", "seller", "buyer", "price", "block_time",
		"items.name as name", "items.description as description", "items.category as category").Joins("left join items on sales.dci = items.dci")

	//按照作品创建时间查询
	if params.IsBlockTimeSearch() {
		begin, end, err := params.Convert()
		if err != nil {
			log.Logger.Debug("error", zap.Error(err), zap.String("code", err.Error()))
			ctx.JSON(http.StatusBadRequest, ErrorResponse(err))
		}
		db = db.Where("sales.block_time between ? and ?", begin, end)
	}

	//按照作品名称去查找
	if params.IsNameSearch() {
		db = db.Where("name like ?", fmt.Sprintf("%s%s%s", "%", params.Name, "%"))
	}
	//按照作品类型去查找
	if params.IsItemTypeSearch() {
		db = db.Where("category = ?", params.Category)
	}

	if params.IsPagination() {
		db = db.Limit(int(params.PageSize)).Offset(int((params.Current - 1) * params.PageSize))
	}
	err = db.Where(model.Sale{DCI: params.DCI, Seller: params.Seller, Buyer: params.Buyer}).Find(&record).Error
	if err != nil {
		log.Logger.Debug("error", zap.Error(err), zap.String("code", errDBError.Error()))
		ctx.JSON(http.StatusInternalServerError, ErrorResponse(errDBError))
		return
	}
	ctx.JSON(http.StatusOK, SuccessResponse(record))
}
